package icu.sehnen.fitness.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import icu.sehnen.fitness.entity.Permission;
import icu.sehnen.fitness.entity.User;
import icu.sehnen.fitness.mapper.UserMapper;
import icu.sehnen.fitness.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.sehnen.fitness.utils.RedisUtil;
import icu.sehnen.fitness.utils.jwt.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author sehnen
 * @since 2021-04-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public User getUserByName(String name) {


        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",name);
        User user=userMapper.selectOne(queryWrapper);
        System.out.println(user);
     //   Assert.isTrue(user!=null,"您输入的账户不存在");
        return   user;
    }


//    代码写的不规范
    @Override
    public List<Permission> getPermissionsByUserId(Long id) {
        if(!redisTemplate.hasKey("permission:list")){
            List<Permission> permissionList=userMapper.getPermissionByUserId(id) ;
            redisTemplate.opsForList().leftPushAll("permission:list", permissionList);
        }
        return    redisTemplate.opsForList().range("permission:list", 0, -1);

    }

    @Override
    public String login(User user) {
        String username = user.getUsername();
        Assert.notNull(username,"账号必须不能为空");
        String password = user.getPassword();
        Assert.notNull(password,"密码必须不能为空");
        User userByName = getUserByName(username);
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        if(matches){
            return jwtTokenUtil.generateToken(userByName);
        }
        return null;
    }
}
